package com.yyy.saga.dao;

import com.yyy.saga.entity.TransferTransaction;
import java.math.BigDecimal;
import java.sql.*;

/**
 * Saga模式转账事务数据访问层
 */
public class TransferTransactionDao {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/distributed_transaction";
    private static final String USER = "root";
    private static final String PASS = "root";

    /**
     * 创建转账事务记录
     */
    public boolean createTransaction(String transactionId, String fromUserId,
                                   String toUserId, BigDecimal amount) throws SQLException {
        String sql = "INSERT INTO saga_transfer_transaction " +
                    "(transaction_id, from_user_id, to_user_id, amount, status) " +
                    "VALUES (?, ?, ?, ?, 'PROCESSING')";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, transactionId);
            stmt.setString(2, fromUserId);
            stmt.setString(3, toUserId);
            stmt.setBigDecimal(4, amount);

            return stmt.executeUpdate() > 0;
        }
    }

    /**
     * 更新事务状态
     */
    public boolean updateStatus(String transactionId, String status) throws SQLException {
        String sql = "UPDATE saga_transfer_transaction SET status = ? WHERE transaction_id = ?";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, status);
            stmt.setString(2, transactionId);

            return stmt.executeUpdate() > 0;
        }
    }

    /**
     * 查询事务记录
     */
    public TransferTransaction getByTransactionId(String transactionId) throws SQLException {
        String sql = "SELECT * FROM saga_transfer_transaction WHERE transaction_id = ?";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, transactionId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    TransferTransaction transaction = new TransferTransaction();
                    transaction.setId(rs.getLong("id"));
                    transaction.setTransactionId(rs.getString("transaction_id"));
                    transaction.setFromUserId(rs.getString("from_user_id"));
                    transaction.setToUserId(rs.getString("to_user_id"));
                    transaction.setAmount(rs.getBigDecimal("amount"));
                    transaction.setStatus(rs.getString("status"));
                    return transaction;
                }
            }
        }
        return null;
    }
}
